//
//  FileManager.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/12/11.
//

import Foundation

class FileManagerHelper {
    // 获取Doc目录
    static func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let documentsDirectory = paths[0]
        return documentsDirectory
    }

    // 创建目录
    static func createFolder(parentFolder: URL, folderName: String) -> (Bool, Error?) {
        let manager = FileManager.default
        var isDir:ObjCBool = true

        do {
            let folder = parentFolder.appendingPathComponent(folderName, isDirectory: true)
            if !FileManager.default.fileExists(atPath: folder.relativeString, isDirectory: &isDir) {
                try manager.createDirectory(at: folder, withIntermediateDirectories: true, attributes: nil)
            }

            return (true, nil)
        } catch {
            return (false, error)
        }
    }

    static func getLogDirectory() -> URL {
        var isDir:ObjCBool = true
        let folder = getDocumentsDirectory().appendingPathComponent("Logs", isDirectory: true)
        if !FileManager.default.fileExists(atPath: folder.relativeString, isDirectory: &isDir) {
            try! FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true, attributes: nil)
        }
        return folder
    }

    static func getTodayLogFile(_ reset: Bool = false) -> URL {
        let filename = Date().todayString + ".txt"
        let logFile = getLogDirectory().appendingPathComponent(filename)

        if reset && FileManager.default.fileExists(atPath: logFile.absoluteString) {
            try! FileManager.default.removeItem(atPath: logFile.absoluteString)
        }

        return logFile
    }
}
